import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import router from 'umi/router'
import { DatePicker, Radio, Icon, Input, Select } from 'antd';
import React, { useState, useCallback, useRef, useEffect } from 'react';
import { useBoolean } from '@umijs/hooks';
import ProTable from '@ant-design/pro-table';
import { queryAuditTable, queryAuditProgress } from './service'; //请求方法
import moment from 'moment';
import { useActivate } from 'react-activation';

import styles from './index.less'

import AuditProgressModal from './components/AuditProgressModal'
import AuthComponent from '@/components/Authorized/AuthComponent';

// 设置时间
const nowTimeStamp = Date.now();
const now = new Date(nowTimeStamp);
const { Option } = Select;

const TableList = (props) => {
  // 计算高度
  const [height, controlH] = useState(300);
  const [isCollapse, controlC] = useState(true);
  useEffect(() => {
    if (isCollapse) {
      controlH(document.body.clientHeight - 380.5);
    } else {
      controlH(document.body.clientHeight - 428.5);
    }
  }, [isCollapse])

  const { location: { state } } = props;
  const [auditModalVisible, handleAuditModalVisible] = useState(false);// 审核流程弹框
  const [auditProgressData, handleAuditProgressData] = useState([]); // 审核流程内容
  // 控制补偿子类型的显示
  const { state: subtypeHideSearch, setTrue:setSubtypeHideSearchTrue, setFalse:setSubtypeHideSearchFalse } = useBoolean(true);
  const [isFromIndex, handleIsFromIndex] = useState(true)

  const actionRef = useRef();
  const searchRef = useRef();
  const ref = useRef();
  const reloadTable = useCallback(function reloadData() {
    if (searchRef.current) {
      searchRef.current.click();
    }
  }, []);

  // 从详情跳转到列表页，刷新表格数据
  useActivate(() => {
    if (state && state.refreshPage) {
      reloadTable()
    } else if (state && state.allAudit) {
      handleIsFromIndex(true)
      reloadTable()
    }
  })

  const [dataScope, setDataScope] = useState('1'); // 审核/已审核/全部
  // 设置审核类型
  const onScopeChange = useCallback(e => {
    setDataScope(e.target.value);
  }, []);

  // 防止多次请求
  const [inited, setInited] = useState(false)
  // 第一次加载
  const [firstLoad, setFirstLoad] = useState(true)
  useEffect(() => {
    if (actionRef.current && inited) {
      reloadTable();
    } else {
      setInited(true)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dataScope])

  // 搜索
  const beforeSearchSubmit = useCallback(params => {
    params['startDate'] = params.startDate ? params.startDate.format('YYYY-MM-DD') : '';
    params['endDate'] = params.endDate ? params.endDate.format('YYYY-MM-DD') : '';

    if (!isCollapse) {
      handleIsFromIndex(false)
      return { ...params, type: dataScope }
    } else {
      if (event.target.querySelector('span') && event.target.querySelector('span').innerText === '查 询') {
        if (Object.keys(params).indexOf('startDate') === -1) {
          params.startDate = ''
        }
        if (Object.keys(params).indexOf('endDate') === -1) {
          params.endDate = ''
        }
        handleIsFromIndex(false)
      } else if (event.target.querySelector('span') && event.target.querySelector('span').innerText === '重 置') {
        handleIsFromIndex(false)
        ref.current.setFieldsValue({
          startDate: moment(),
          endDate: moment()
        });
        setSubtypeHideSearchTrue();
      }
      return { ...params, type: dataScope }
    }

  }, [dataScope]);

  const [_startDate, setStartDate] = useState(now)
  const [_endDate, setEndDate] = useState(now)

  const formatFlightNo = (val) => {
    if (!val) {
      return '';
    } else if (val.length < 3 || /^\D/.test(val)) {
      return ''.toUpperCase.call(val);
    } else if (/^\d{2}/.test(val)) {
      return `3U${val}`;
    } else {
      return val;
    }
  }
  /**
 * 查看补偿单审批流程
 */
  const showAuditProcess = async fields => {
    queryAuditProgress({ orderId: fields.orderId }).then(res => {
      handleAuditProgressData(res)
      handleAuditModalVisible(true);
    })
  }

  /**
    * 补偿单审核页面
    */
  const toAudioDetail = async fields => {
    if (AuthComponent.getAuth('compensation.audit.viewDetail')) {
      let compensationAuditState = {
        orderId: fields.orderId,
        taskId: fields.taskId,
      };
      window.localStorage.setItem('compensationAuditState',JSON.stringify(compensationAuditState))
      router.push({
        pathname: '/compensation/CompensationAudit/AuditDetail',
        state: compensationAuditState
      })
    }
  }
  const columns = [
    {
      title: '操作',
      width: 90,
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <span onClick={() => {
          showAuditProcess(record);
        }}
          style={{ cursor: "pointer" }}
        >
          <Icon type="deployment-unit" />
        </span>
      ],
    },
    {
      title: '补偿单状态',
      width: 120,
      dataIndex: 'status',
      filters: [
        // {text: '草稿',value: '0'},
        {text: '审核中', value: '1'},
        {text: '通过', value: '2'},
        {text: '生效', value: '3'},
        {text: '已关闭', value: '4'},
        {text: '未通过', value: '5'},
        {text: '驳回', value: '6'},
        {text: '逾期', value: '8'},
        // todo 新增加两种状态，接口需要支持 暂时没有已发放
        {text: '已发放', value: '10'},
        {text: '注销', value: '9'},
      ],
      valueEnum: {
        '': {text: '全部'},
        // '0': {text: '草稿'},
        1: {text: '审核中'},
        2: {text: '通过'},
        3: {text: '生效'},
        4: {text: '已关闭'},
        5: {text: '未通过'},
        6: {text: '驳回'},
        8: {text: '逾期'},
        // todo 新增加两种状态，接口需要支持 暂时没有已发放
        10: {text: '已发放'},
        9: {text: '注销'},

      }
    },
    {
      title: '审核意见',
      width: 120,
      dataIndex: 'auditStatic',
      hideInSearch: true,
      renderText: (text, row) => {
        if (row.isAudit === '1') {
          return '待审核'
        } else {
          switch (row.auditStatic) {
            case '0':
              return '同意'
            case '1':
              return '不同意'
            case '2':
              return '驳回'
            case '3':
              return '发起'
            default:
              return ' '
          }
        }
      }
    },
    {
      title: '航班号',
      dataIndex: 'flightNo',
      width: 90,
      renderFormItem: (_, { type, defaultRender, ...rest }) => {
        return <Input
          {...rest}
          onChange= {e => {
            e.target.value = formatFlightNo(e.target.value);
            rest.onChange(e.target.value)
          }}
          allowClear maxLength={6} placeholder="3U" />;
      }
    },
    {
      title: '补偿单号',
      dataIndex: 'orderId',
      width: 180,
    },
    {
      title: '航班日期',
      width: 150,
      dataIndex: 'flightDate',
      hideInSearch: true
    },
    {
      title: '航班开始日期',
      hideInTable: true,
      dataIndex: 'startDate',
      order: 5,
      renderFormItem: (_, { defaultRender, ...rest  }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}
            {...rest}
            onChange = {e =>{
              setStartDate(e)
              rest.onChange(e)
            }}
            disabledDate={(current)=>{
              return current && current < moment(_endDate).subtract('180','days');
            }}
          />
        );
      },
    },
    {
      title: '航班结束日期',
      hideInTable: true,
      order: 4,
      dataIndex: 'endDate',
      renderFormItem: (_, {  defaultRender, ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}
            {...rest}
            onChange = {(e) =>{
              setEndDate(e)
              rest.onChange(e)
            }}
            disabledDate={(current)=>{
              return current && current > moment(_startDate).add(180, "days");
            }}
          />
        );
      },
    },
    {
      title: '航段',
      width: 120,
      ellipsis: true,
      dataIndex: 'segment',
      hideInSearch: true,
    },
    {
      title: '补偿类型',
      width: 120,
      dataIndex: 'payType',
      filters:false,
      valueEnum: {
        '': {
          text: '全部',
        },
        0: {
          text: '不正常航班',
        },
        1: {
          text: '异常行李',
        },
        2: {
          text: '旅客超售',
        }
      },
      renderFormItem: (_, { ...rest }) => {
        return (
          <Select
          showSearch
          placeholder='请选择'
          defaultActiveFirstOption={false}
          showArrow={false}
          filterOption={true}
          notFoundContent={null}
          {...rest}
          onChange={(val)=>{
            // 选择的类型是异常行李就显示补偿子类型，否则就隐藏
            val == 1 ? setSubtypeHideSearchFalse() : setSubtypeHideSearchTrue();
            rest.onChange(val);
            setTimeout(() => {
              ref.current.setFieldsValue({
                orderSubType:'',
              });
            }, 0);

          }}
        >
          <Option value={''}>全部</Option>
          <Option value={0}>不正常航班</Option>
          <Option value={1}>异常行李</Option>
          <Option value={2}>旅客超售</Option>
        </Select>
        );
      },
    },
    {
      title: '补偿子类型',
      width: 120,
      dataIndex: 'orderSubType',
      hideInSearch: subtypeHideSearch,
      filters:false,
      valueEnum: {
        '': {
          text: '全部',
        },
        0: {
          text: '临时补偿',
        },
        1: {
          text: '结案补偿',
        },
        2: {
          text: '箱包补偿',
        },
      },
    },
    {
      title: '总人数',
      dataIndex: 'paxTotalCount',
      hideInSearch: true,
      width: 90
    },
    {
      title: '补偿金额',
      width: 120,
      dataIndex: 'totalMoney',
      hideInSearch: true,
    },
    {
      title: '申请人',
      dataIndex: 'applyUser',
      hideInSearch: true,
      width: 120
    },
    {
      title: '申请时间',
      width: 150,
      dataIndex: 'applyTime',
      hideInSearch: true,
    },
    {
      title: '任务单号',
      width: 160,
      dataIndex: 'taskId',
      hideInTable: true,
      hideInSearch: true
    },
  ];

  return (
    <>
      <ProTable
        size='small'
        formRef={ref}
        options={{density: false,fullScreen:true, reload:false, setting:true}}
        tableAlertRender={false}
        className={`${styles.comAuditTable} rest-pro-table-form-compact ${isCollapse?'':'collapse'}`}
        scroll={{ x: 1300, y: height }}
        // eslint-disable-next-line react/jsx-no-duplicate-props
        pagination={{
          showSizeChanger: true,
          showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 项`
        }}
        columns={columns}
        headerTitle={
          <div>
            <span style={{ paddingRight: 10, fontWeight: "bold", color: "#000" }}>补偿申请列表</span>
            <Radio.Group onChange={onScopeChange} value={dataScope} buttonStyle="solid">
              <Radio.Button value="0">全部</Radio.Button>
              <Radio.Button value="1">待审核</Radio.Button>
              <Radio.Button value="2">已审核</Radio.Button>
            </Radio.Group>
          </div>
        }
        onRow={record => {
          return {
            onDoubleClick: event => {
              toAudioDetail(record)
            }
          }
        }}
        actionRef={actionRef}
        rowKey="orderId"
        beforeSearchSubmit={beforeSearchSubmit}
        search={{
          searchText: (
            <span ref={searchRef} href>
              查询
            </span>
          ),
          onCollapse: val => {
            controlC(val);
          }
        }}
        request={params => {
          params['type'] = dataScope;
          if (!params['startDate'] && !params['endDate']) {
            // setFirstLoad(false)
            params['startDate'] = moment().format('YYYY-MM-DD');
            params['endDate'] = moment().format('YYYY-MM-DD');
            ref.current.setFieldsValue({
              startDate: moment(),
              endDate: moment()
            })
          }
          if (params['payType'] == undefined) {
            ref.current.setFieldsValue({
              payType: ''
            })
          }
          if (!params['status']) {
            ref.current.setFieldsValue({
              status: ''
            })
          }
          
          if (state && state.allAudit && isFromIndex) {
            ref.current.setFieldsValue({
              startDate: '',
              endDate: moment()
            })
            params['startDate'] = '';
            params['endDate'] = moment().format('YYYY-MM-DD');
          }

          return queryAuditTable(params);
        }}
      />
      <AuditProgressModal
        auditModalVisible={auditModalVisible}
        auditProgressData={auditProgressData}
        onClose={() => {
          handleAuditModalVisible(false);
        }}>
      </AuditProgressModal>

    </>
  );
};

export default Form.create()(TableList);
